import qs from 'qs'
import Taro from '@tarojs/taro'
import _ from 'lodash'
import { TOKEN_KEY, LOCAL_STORAGE_PRE } from './constant'
export function queryToMap(string) {
  if (!string) return new Map()
  const stringToObj = qs.parse(string) || {}
  const arr = Object.entries(stringToObj).map(i => {
    return i
  })
  return new Map(arr)
}

export function removeToken() {
  const tokenKey = TOKEN_KEY || ''
  removeStorage(tokenKey)
}

export function setToken(token) {
  const tokenKey = TOKEN_KEY || ''
  setStorage(tokenKey, token)
}

export function getToken() {
  const tokenKey = TOKEN_KEY || ''
  return getStorage(tokenKey)
}

export function removeStorage(key) {
  const pre = LOCAL_STORAGE_PRE || ''
  return Taro.removeStorageSync(`${pre}-${key}`)
}

export function setStorage(key, value) {
  const pre = LOCAL_STORAGE_PRE || ''
  Taro.setStorageSync(`${pre}-${key}`, value)
}

export function getStorage(key) {
  const pre = LOCAL_STORAGE_PRE || ''
  return Taro.getStorageSync(`${pre}-${key}`)
}

/**
 * 递归对数据进行分类，并对数据根据target进行筛选
 * @param {*} menu 源数据
 * @param {*} targets 需要筛选的id
 * @returns
 */
const getMenuObj = (menu, targets) => {
  const menus = []
  const funcs = []
  menu.subMenus &&
    menu.subMenus.forEach(i => {
      if (i.subMenus && i.subMenus.length) {
        const menuObj = getMenuObj(i, targets)
        if (menuObj.menus.length || menuObj.funcs.length) {
          menus.push(menuObj)
        }
      } else {
        const isHave =
          (i.functionId && targets.includes(i.functionId.toString())) ||
          !targets ||
          !targets.length

        isHave && funcs.push(i)
      }
    })
  return Object.assign(menu, { menus, funcs })
}

/**
 * 构建分类后的菜单列表，并对数据根据target进行筛选
 * @param {*} list 源数据
 * @param {*} target 需要筛选的id
 * @returns
 */
export function getMenuList(list, targets) {
  if (!list || !list.length) return []
  const result = list
    .map(i => {
      const obj = getMenuObj(i, targets)
      return obj
    })
    .filter(i => i.menus.length || i.funcs.length)
  return result
}

/**
 * 递归处理 数据铺平
 * @param {*} menus
 * @returns
 */
export function munusGetFuncs(menus) {
  if (!menus || !menus.length) return []
  let funcs = []
  menus.forEach(i => {
    if (i.funcs) {
      funcs = funcs.concat(i.funcs)
    }
    if (i.subMenus && i.subMenus.length) {
      funcs = funcs.concat(munusGetFuncs(i.subMenus))
    }
  })
  return funcs
}
